package com.marisfrolg.util;

import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Message;

import com.marisfrolg.entity.BinActualItemInfo;

public class WebServicesUtil {
	public static final String NAMESPACE = "http://tempuri.org/";
	public static final String METHOD_ACTION_CHECK = "Check";
	public static final String METHOD_ACTION_LOGIN = "Login";
	public static final String METHOD_ACTION_GETBINSTOCK = "GetBinStock";
	public static final String METHOD_ACTION_GETPRODUCTSTOCK = "GetProductStock";
	public static final String METHOD_ACTION_UpdateBinActual = "UpdateBinActual";
	public static final String METHOD_ACTION_UpdateBinActual2 = "UpdateBinActual2";
	public static final String METHOD_ACTION_GetDifference = "GetDifference";
	public static final String METHOD_ACTION_GetWHO = "GetWHO";
	public static final String METHOD_ACTION_SubmitWHO = "SubmitWHO";
	public static final String METHOD_ACTION_MoveBINSTOCK = "MoveBINSTOCK";
	public static final String METHOD_ACTION_MoveBINSTOCKS = "MoveBINSTOCKS";
	public static final String METHOD_ACTION_getQUEUE = "getQUEUE";
	public static final String METHOD_ACTION_MoveBIN = "MoveBIN";
	public static final String METHOD_ACTION_MoveBINS = "MoveBINS";
	public static final String METHOD_ACTION_getWOByQUEUENAME = "getWOByQUEUENAME";
	public static final String METHOD_ACTION_LOGOUT = "logout";
	public static final String METHOD_ACTION_getINBOUND = "getINBOUND";
	public static final String METHOD_ACTION_submitINBOUND = "submitINBOUND";
	public static final String URL_ACTION_CHECK = "http://tempuri.org/Check";
	public static final String URL_ACTION_LOGIN = "http://tempuri.org/Login";
	public static final String URL_ACTION_GETBINSTOCK = "http://tempuri.org/GetBinStock";
	public static final String URL_ACTION_UpdateBinActual = "http://tempuri.org/UpdateBinActual";
	public static final String URL_ACTION_UpdateBinActual2 = "http://tempuri.org/UpdateBinActual2";
	public static final String URL_ACTION_GETPRODUCTSTOCK = "http://tempuri.org/GetProductStock";
	public static final String URL_ACTION_GetDifference = "http://tempuri.org/GetDifference";
	public static final String URL_ACTION_GetWHO = "http://tempuri.org/GetWHO";
	public static final String URL_ACTION_SubmitWHO = "http://tempuri.org/SubmitWHO";
	public static final String URL_ACTION_MoveBINSTOCK = "http://tempuri.org/MoveBINSTOCK";
	public static final String URL_ACTION_MoveBINSTOCKS = "http://tempuri.org/MoveBINSTOCKS";
	public static final String URL_ACTION_MoveBIN = "http://tempuri.org/MoveBIN";
	public static final String URL_ACTION_MoveBINS = "http://tempuri.org/MoveBINS";
	public static final String URL_ACTION_getQUEUE = "http://tempuri.org/getQUEUE";
	public static final String URL_ACTION_getWOByQUEUENAME = "http://tempuri.org/getWOByQUEUENAME";
	public static final String URL_ACTION_LOGOUT = "http://tempuri.org/logout";
	public static final String URL_ACTION_getINBOUND = "http://tempuri.org/getINBOUND";
	public static final String URL_ACTION_submitINBOUND = "http://tempuri.org/submitINBOUND";
	public static final int ACTION_LOGIN = 1;
	public static final int ACTION_GETBINSTOCK = 10;
	public static final int ACTION_UpdateBinActual = 11;
	public static final int ACTION_UpdateBinActual2 = 12;
	public static final int ACTION_GetDifference = 20;
	public static final int ACTION_GETPRODUCTSTOCK = 25;
	public static final int ACTION_GetWHO = 100;
	public static final int ACTION_SubmitWHO = 120;
	public static final int ACTION_MoveBINSTOCK = 140;
	public static final int ACTION_MoveBINSTOCKS = 142;
	public static final int ACTION_MoveBIN = 170;
	public static final int ACTION_MoveBINS = 172;
	public static final int ACTION_getQUEUE = 180;
	public static final int ACTION_getWOByQUEUENAME = 190;
	public static final int ACTION_LOGOUT = 1000;
	public static final int ACTION_getINBOUND = 200;
	public static final int ACTION_submitINBOUND = 300;
	// public static final String URL =
	// "http://service1.marisfrolg.com/EWMBOOSTER/WebService.asmx";
	 public static final String URL ="http://192.168.2.8/EWMBOOSTER/WebService.asmx";
//	public static final String URL = "http://192.168.1.91/EWMBOOSTER/WebService.asmx";
	// public static final String URL =
	// "http://210.75.13.197/EWMBOOSTER/WebService.asmx";
	public static final int TIMEOUT = -100;
	public static final int NETUNREACHABLE = -200;
	private Handler handler;
	private Context context;
	private static boolean connTimeout=false;
	private static boolean msgSendFlag=false;
	private  int checktime = 3000;
	private static int timeoutTimes=2;
	private Object lockObj=new Object();

	public WebServicesUtil(Context context, Handler handler) {
		this.context = context;
		this.handler = handler;
		timeoutTimes=2;
	}
	
	public void call(final int action, final Map<String, Object> params,
			final String url, final String method) {
		if(!isNetworkConnected()){
			Message msg = new Message();
			msg.what = NETUNREACHABLE;
			handler.sendMessage(msg);
			return;
		}
		new Thread() {
			@Override
			public void run() {
				synchronized (lockObj) {
					msgSendFlag=false;
					connTimeout=false;
//					System.out.println("tip:start~~~~~~~set false");
					Object detail;
					SoapObject rpc = null;
					try {
						rpc = new SoapObject(NAMESPACE, METHOD_ACTION_CHECK);
						SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
								SoapEnvelope.VER11);
						envelope.bodyOut = rpc;
						envelope.dotNet = true;
						envelope.setOutputSoapObject(rpc);
						HttpTransportSE ht = new HttpTransportSE(URL);
						ht.debug = true;
						//-------时间控制器,超时则不请求webservice
						Timer timer = new Timer();  
						TimerTask timeTask=new TimerTask() {
							public void run() {
								sendUnreachableMsg();
								timeoutTimes++;
								if(timeoutTimes%3==0){
									WifiAdmin wa=new WifiAdmin(context);
									wa.disconnect();
									wa.reconnect();
								}
//								System.out.println("tip:"+"time----"+this.scheduledExecutionTime());
							}
						};
			            timer.schedule(timeTask, checktime);
			            //网络测试
						ht.call(URL_ACTION_CHECK, envelope);
						detail = envelope.getResponse();
						timeTask.cancel();
						//--------网络测试时间用时是否超时
						if(timeTask.scheduledExecutionTime()!=0||!"0".equals(detail+"")||connTimeout){
							sendUnreachableMsg();
//							System.out.println("tip:超时不继续请求");
							return;
						}
//						System.out.println("tip:未超时继续请求");
						ReadyCall(action, params, url, method);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}.start();

	}
	
	private void sendUnreachableMsg(){
		if(!msgSendFlag){
			Message msg = new Message();
			msg.what = NETUNREACHABLE;
			handler.sendMessage(msg);
			msgSendFlag=true;
		}
	}

//	public void call(final int action, final Map<String, Object> params,
//			final String url, final String method) {
//		if(!isNetworkConnected()){
//			Message msg = new Message();
//			msg.what = NETUNREACHABLE;
//			handler.sendMessage(msg);
//			return;
//		}
//		
//		new Thread() {
//			@Override
//			public void run() {
//				Object detail;
//				SoapObject rpc = null;
//				try {
//					rpc = new SoapObject(NAMESPACE, method);
//					for (String key : params.keySet()) {
//						rpc.addProperty(key, params.get(key));
//					}
//					SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
//							SoapEnvelope.VER11);
//					envelope.bodyOut = rpc;
//					envelope.dotNet = true;
//					envelope.addMapping(NAMESPACE, "Item",
//							BinActualItemInfo.class);
//					envelope.setOutputSoapObject(rpc);
//					HttpTransportSE ht = new HttpTransportSE(URL);
//					// AndroidHttpTransport ht = new AndroidHttpTransport(URL);
//					ht.debug = true;
//					ht.call(url, envelope);
//					// ht.call(null, envelope);
//					// SoapObject result = (SoapObject)envelope.bodyIn;
//					// detail = (SoapObject)SoapPrimitive
//					// result.getProperty("getWeatherbyCityNameResult");
//					detail = envelope.getResponse();
//					// 执行完毕后给handler发送一个空消息
//					Message msg = new Message();
//					msg.what = action;
//					msg.obj = detail;
//					if (msg.what == ACTION_UpdateBinActual
//							|| action == ACTION_UpdateBinActual2) {
//						if (params != null) {
//							msg.arg1 = (Integer) params.get("BINID");
//						}
//					}
//					handler.sendMessage(msg);
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//			}
//		}.start();
//
//	}
	
	public void ReadyCall(final int action, final Map<String, Object> params,
			final String url, final String method) {
		new Thread() {
			@Override
			public void run() {
				Object detail;
				SoapObject rpc = null;
				try {
					rpc = new SoapObject(NAMESPACE, method);
					for (String key : params.keySet()) {
						rpc.addProperty(key, params.get(key));
					}
					SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
							SoapEnvelope.VER11);
					envelope.bodyOut = rpc;
					envelope.dotNet = true;
					envelope.addMapping(NAMESPACE, "Item",
							BinActualItemInfo.class);
					envelope.setOutputSoapObject(rpc);
					HttpTransportSE ht = new HttpTransportSE(URL);
					// AndroidHttpTransport ht = new AndroidHttpTransport(URL);
					ht.debug = true;
					ht.call(url, envelope);
					// ht.call(null, envelope);
					// SoapObject result = (SoapObject)envelope.bodyIn;
					// detail = (SoapObject)SoapPrimitive
					// result.getProperty("getWeatherbyCityNameResult");
					detail = envelope.getResponse();
					// 执行完毕后给handler发送一个空消息
					Message msg = new Message();
					msg.what = action;
					msg.obj = detail;
					if (msg.what == ACTION_UpdateBinActual
							|| action == ACTION_UpdateBinActual2) {
						if (params != null) {
							msg.arg1 = (Integer) params.get("BINID");
						}
					}
					handler.sendMessage(msg);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();

	}
	
	

	public void callS(final int action, final SoapObject rpc, final String url,
			final String method) {
		new Thread() {
			@Override
			public void run() {
				Object detail;
				try {
					SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
							SoapEnvelope.VER11);
					envelope.bodyOut = rpc;
					envelope.dotNet = true;
					envelope.setOutputSoapObject(rpc);
					HttpTransportSE ht = new HttpTransportSE(URL);
					// AndroidHttpTransport ht = new AndroidHttpTransport(URL);
					ht.debug = true;
					ht.call(url, envelope);
					// ht.call(null, envelope);
					// SoapObject result = (SoapObject)envelope.bodyIn;
					// detail = (SoapObject)SoapPrimitive
					// result.getProperty("getWeatherbyCityNameResult");
					detail = envelope.getResponse();
					// 执行完毕后给handler发送一个空消息
					Message msg = new Message();
					msg.what = action;
					msg.obj = detail;
					handler.sendMessage(msg);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	public void callArray(final int action,
			final List<Map<String, Object>> paramsList, final String url,
			final String method) {
		new Thread() {
			@Override
			public void run() {
				Object detail;
				SoapObject rpc = null;
				for (Map<String, Object> params : paramsList) {
					try {
						rpc = new SoapObject(NAMESPACE, method);
						for (String key : params.keySet()) {
							rpc.addProperty(key, params.get(key));
						}
						SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
								SoapEnvelope.VER11);
						envelope.bodyOut = rpc;
						envelope.dotNet = true;
						envelope.addMapping(NAMESPACE, "Item",
								BinActualItemInfo.class);
						envelope.setOutputSoapObject(rpc);
						HttpTransportSE ht = new HttpTransportSE(URL);
						// AndroidHttpTransport ht = new
						// AndroidHttpTransport(URL);
						ht.debug = true;
						ht.call(url, envelope);
						// ht.call(null, envelope);
						// SoapObject result = (SoapObject)envelope.bodyIn;
						// detail = (SoapObject)SoapPrimitive
						// result.getProperty("getWeatherbyCityNameResult");
						detail = envelope.getResponse();
						// 执行完毕后给handler发送一个空消息
						Message msg = new Message();
						msg.what = action;
						msg.obj = detail;
						if (msg.what == ACTION_UpdateBinActual
								|| action == ACTION_UpdateBinActual2) {
							if (params != null) {
								msg.arg1 = (Integer) params.get("BINID");
							}
						}
						handler.sendMessage(msg);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}.start();
	}

	public boolean isNetworkConnected() {
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mNetworkInfo = mConnectivityManager
					.getActiveNetworkInfo();
			if (mNetworkInfo != null) {
				return mNetworkInfo.isAvailable();
			}
		}
		return false;
	}
	
	public static void setConnectionTimeOut(){
		connTimeout=true;
	}

	/**
	 * @return the checktime
	 */
	public int getChecktime() {
		return checktime;
	}

	/**
	 * @param checktime the checktime to set
	 */
	public void setChecktime(int checktime) {
		this.checktime = checktime;
	}
}


